package main

import (
	"errors"
	"flag"
	"fmt"
	"github.com/robfig/cron/v3"
	"log"
	"net"
	"net/http"
	"runtime"
	"strings"
	"time"
)

var (
	port    string
	datFile string
	datUrl  string
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.StringVar(&port, "port", "2060", "HTTP 请求监听端口号")
	flag.StringVar(&datFile, "qqwry", "./qqwry.dat", "纯真 IP 库的地址")
	flag.StringVar(&datUrl, "update", "https://raw.githubusercontent.com/FW27623/qqwry/main/qqwry.dat", "纯真 IP 库的在线更新地址")
	flag.Parse()

	// 加载IP数据库
	IPData.FilePath = datFile

	startTime := time.Now().UnixNano()
	res := IPData.InitIPData()
	if v, ok := res.(error); ok {
		log.Panic(v)
	}
	endTime := time.Now().UnixNano()
	log.Printf("IP 库加载完成 共加载:%d 条 IP 记录, 所花时间:%.1f ms\n", IPData.IPNum, float64(endTime-startTime)/1e6)

	// 添加定时任务
	c := cron.New()
	_, err := c.AddFunc("14 11,16 * * *", updateIP)
	if err != nil {
		log.Fatalf("定时任务添加失败: %v", err)
	} else {
		log.Println("定时任务启动成功")
	}
	c.Start()

	// 下面开始加载 http 相关的服务
	http.HandleFunc("/", findIP)

	log.Printf("开始监听网络端口:%s", port)

	if err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil); err != nil {
		log.Println(err)
	}
}

// findIP 查找 IP 地址的接口
func findIP(w http.ResponseWriter, r *http.Request) {
	res := NewResponse(w, r)

	ip := r.Form.Get("ip")

	if ip == "" {
		remoteIP, err := getRemoteIP(r)
		if err != nil {
			res.ReturnError(http.StatusBadRequest, 200001, "请填写 IP 地址")
			return
		}
		ip = remoteIP
	}

	ips := strings.Split(ip, ",")

	qqWry := NewQQwry()

	if len(ips) == 1 {
		rs := qqWry.Find(ips[0])
		res.ReturnSuccess(rs)
	} else if len(ips) > 1 {
		rs := map[string]ResultQQwry{}
		for _, v := range ips {
			rs[v] = qqWry.Find(v)
		}
		res.ReturnSuccess(rs)
	}
}

func getRemoteIP(r *http.Request) (string, error) {
	ip := r.Header.Get("X-Forward-For")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}
	ip = r.Header.Get("Proxy-Client-IP")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}
	ip = r.Header.Get("WL-Proxy-Client-IP")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}
	ip = r.Header.Get("HTTP_CLIENT_IP")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}
	ip = r.Header.Get("X-Real-IP")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}

	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return "", err
	}

	if net.ParseIP(ip) != nil {
		return ip, nil
	}

	return "", errors.New("no valid ip found")
}

func updateIP() {
	IPData.FilePath = datFile

	startTime := time.Now().UnixNano()
	res := IPData.UpdateIPData()
	if v, ok := res.(error); ok {
		log.Panic(v)
	}
	endTime := time.Now().UnixNano()
	log.Printf("IP 库加载完成 共加载:%d 条 IP 记录, 所花时间:%.1f ms\n", IPData.IPNum, float64(endTime-startTime)/1e6)
}
